package com.kantboot.system.dict.service.impl;

import cn.hutool.core.thread.ThreadUtil;
import com.alibaba.fastjson2.JSON;
import com.kantboot.api.google.translate.service.IGoogleTranslateService;
import com.kantboot.global.data.change.annotaion.DataChange;
import com.kantboot.global.data.change.common.CommonDataChangeKey;
import com.kantboot.system.dict.dao.repository.SysDictI18nRepository;
import com.kantboot.system.dict.domain.dto.ToGobleBatchTextDTO;
import com.kantboot.system.dict.domain.dto.ToGobleDTO;
import com.kantboot.system.dict.domain.dto.ToGobleBatchDTO;
import com.kantboot.system.dict.domain.entity.SysDictI18n;
import com.kantboot.system.dict.domain.entity.SysLanguage;
import com.kantboot.system.dict.service.ISysDictI18nService;
import com.kantboot.system.dict.service.ISysLanguageService;
import jakarta.annotation.Resource;
import lombok.SneakyThrows;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class SysDictI18nServiceImpl implements ISysDictI18nService {

    @Resource
    private ISysLanguageService languageService;

    @Resource
    private IGoogleTranslateService googleTranslateService;

    @Resource
    private SysDictI18nRepository dictI18nRepository;

    @DataChange(key = CommonDataChangeKey.CLIENT_INIT)
    public List<SysDictI18n> toGoble(String text,String sourceLanguageCode, String dictGroupCode, String dictCode) {

        List<SysDictI18n> i18nList = new ArrayList<>();

        // 去除首尾空格
        text = text.trim();
        // 查询数量
        Long l = dictI18nRepository.countByLanguageCodeAndDictGroupCodeAndValue(sourceLanguageCode, dictGroupCode, text);
        if(l>0){
            System.out.println("已存在国际化词："+text);
            return null;
        }

        // 获取翻译的文本
        String translateTextToEn = googleTranslateService.translateText(
                sourceLanguageCode,
                "en",
                text
        );

        // 如果dictCode为空，就用翻译的文本，并取出特殊符号、空格改驼峰式
        if(dictCode == null || dictCode.isEmpty()){
            // 去除特殊符号，除空格以外
            dictCode = translateTextToEn.replaceAll("[^a-zA-Z0-9 ]", "");
            String[] dictCodeSplit = dictCode.split(" ");
            StringBuilder sb = new StringBuilder();
            for (String s : dictCodeSplit) {
                sb.append(s.substring(0, 1).toUpperCase()).append(s.substring(1));
            }
            dictCode = sb.toString();
            // 首字母改成小写
            dictCode = dictCode.substring(0, 1).toLowerCase() + dictCode.substring(1);
        }

        // 保存到国际化字典
        SysDictI18n dictI18nEn = new SysDictI18n();
        dictI18nEn.setLanguageCode("en");
        dictI18nEn.setDictCode(dictCode);
        dictI18nEn.setDictGroupCode(dictGroupCode);
        dictI18nEn.setValue(translateTextToEn);
        dictI18nRepository.insert(dictI18nEn);
        i18nList.add(dictI18nEn);
        System.out.println("dictI18nEn = " + JSON.toJSONString(dictI18nEn));

        // 将源语言的文本保存到国际化字典
        SysDictI18n dictI18nSource = new SysDictI18n();
        dictI18nSource.setLanguageCode(sourceLanguageCode);
        dictI18nSource.setDictCode(dictCode);
        dictI18nSource.setDictGroupCode(dictGroupCode);
        dictI18nSource.setValue(text);
        dictI18nRepository.insert(dictI18nSource);
        i18nList.add(dictI18nSource);
        System.out.println("dictI18nSource = " + JSON.toJSONString(dictI18nSource));


        List<SysLanguage> bySupport = languageService.getBySupport();

        for (SysLanguage sysLanguage : bySupport) {
            // 目标语言编码
            String targetLanguageCode = sysLanguage.getCode();

            // 如果目标语言不是英文，且不是源语言
            if (!targetLanguageCode.equals("en") && !targetLanguageCode.equals(sourceLanguageCode)) {

                String targetLanguageCode2 = targetLanguageCode;
                if(targetLanguageCode.equals("zh_MO")){
                    targetLanguageCode2 = "zh_HK";
                }
                // 获取翻译的文本
                String translateText = googleTranslateService.translateText(
                        sourceLanguageCode,
                        targetLanguageCode2,
                        text
                );

                // 保存到国际化字典
                SysDictI18n dictI18n = new SysDictI18n();
                dictI18n.setLanguageCode(targetLanguageCode);
                dictI18n.setDictCode(dictCode);
                dictI18n.setDictGroupCode(dictGroupCode);
                dictI18n.setValue(translateText);
                dictI18nRepository.insert(dictI18n);
                i18nList.add(dictI18n);
                System.out.println("dictI18n = " + JSON.toJSONString(dictI18n));
            }

        }


        return i18nList;

    }

    @Override
    public void toGobleBatch(ToGobleBatchDTO toGobleBatchDTO) {
        List<ToGobleDTO> params = toGobleBatchDTO.getParams();
        for (ToGobleDTO param : params) {
            toGoble(param.getText(), toGobleBatchDTO.getSourceLanguageCode(), param.getDictGroupCode(), param.getDictCode());
        }
    }

    @SneakyThrows
    @Override
    public void toGlobalBatchText(ToGobleBatchTextDTO toGobleBatchTextDTO) {
        for (String text : toGobleBatchTextDTO.getTexts()) {
            Thread.sleep(100);
            ThreadUtil.execute(()->{
                toGoble(text, toGobleBatchTextDTO.getSourceLanguageCode(), toGobleBatchTextDTO.getDictGroupCode(), null);
            });
        }
    }

    @Override
    public List<SysDictI18n> getDict(String languageCode, String dictGroupCode) {
        return dictI18nRepository.findByDictGroupCodeAndLanguageCode(dictGroupCode, languageCode);
    }

    @Override
    public String toTargetLanguageCode(ToGobleDTO toGobleDTO) {
        // 文字
        String text = toGobleDTO.getText();

        // 源语言编码
        String sourceLanguageCode = toGobleDTO.getSourceLanguageCode();

        // 字典分组编码
        String dictGroupCode = toGobleDTO.getDictGroupCode();

        // 字典编码
        String dictCode = toGobleDTO.getDictCode();

        // 目标语言编码
        String targetLanguageCode = toGobleDTO.getTargetLanguageCode();

        List<SysDictI18n> list =
                dictI18nRepository.findByLanguageCodeAndDictGroupCodeAndDictCode(sourceLanguageCode, dictGroupCode, dictCode);
        if(list!=null&&!list.isEmpty()){
            return list.get(0).getValue();
        }

        // 如果目标语言是源语言，直接加入字典
        if(targetLanguageCode.equals(sourceLanguageCode)){
            SysDictI18n dictI18n = new SysDictI18n();
            dictI18n.setLanguageCode(targetLanguageCode);
            dictI18n.setDictCode(dictCode);
            dictI18n.setDictGroupCode(dictGroupCode);
            dictI18n.setValue(text);
            dictI18nRepository.save(dictI18n);
            return dictI18n.getValue();
        }

        String targetLanguageCode2 = targetLanguageCode;
        if(targetLanguageCode.equals("zh_MO")){
            targetLanguageCode2 = "zh_HK";
        }
        // 获取翻译的文本
        String translateText = googleTranslateService.translateText(
                sourceLanguageCode,
                targetLanguageCode2,
                text
        );

        // 保存到国际化字典
        SysDictI18n dictI18n = new SysDictI18n();
        dictI18n.setLanguageCode(targetLanguageCode);
        dictI18n.setDictCode(dictCode);
        dictI18n.setDictGroupCode(dictGroupCode);
        dictI18n.setValue(translateText);
        dictI18nRepository.save(dictI18n);


        return dictI18n.getValue();
    }
}
